import { login, getUserInfo } from '@/api/user';
import { getToken, removeToken, setLoginTimestamp, setToken } from '@/utils/auth';

export default {
  namespaced: true,
  state: {
    userInfo: null,
    token: getToken(),
  },
  mutations: {
    updateUserNameAndPhoto(state, { name, photo }) {
      state.userInfo.base.username = name;
      state.userInfo.detail.username = name;
      state.userInfo.detail.staffPhoto = photo;
    },

    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    setToken(state, token) {
      state.token = token;
      setToken(token);
    },
    removeToken(state) {
      state.token = null;
      removeToken();
    },
  },
  actions: {
    logout(ctx) {
      ctx.commit('setUserInfo', null);
      ctx.commit('removeToken');
    },
    getUserInfo(ctx) {
      return getUserInfo().then(userInfo => {
        ctx.commit('setUserInfo', userInfo);
        return userInfo;
      });
    },
    login(ctx, data) {
      return login(data).then(token => {
        ctx.commit('setToken', token);
        setLoginTimestamp();
      });
    },
  },
  getters: {},
};
